//
//  BannerView.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/12/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit

final class BannerView: UIView {
    
    private lazy var overlayView: UIView = {
        let view = UIView()
        view.layer.cornerRadius = 7
        return view
    }()
    
    private lazy var bannerImgView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.layer.cornerRadius = 7
        return imageView
    }()
    
    private lazy var titleLbl: UILabel = {
        let lbl = UILabel()
        lbl.font = UIFont.systemFont(ofSize: 21, weight: .bold)
        lbl.textColor = .white
        lbl.sizeToFit()
        lbl.textAlignment = .left
        return lbl
    }()
    
    private lazy var hintLbl: UILabel = {
        let lbl = UILabel ()
        lbl.font = UIFont.systemFont(ofSize: 13, weight: .regular)
        lbl.textColor = .white
        lbl.sizeToFit()
        lbl.textAlignment = .left
        return lbl
    }()
    
    init () {
        super.init(frame: .zero)
        self.addViews()
        self.clipsToBounds = false
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public func update (image: UIImage?, title: String, message: String) {
        titleLbl.text = title
        hintLbl.text = message
        bannerImgView.image = image
    }
    
}

extension BannerView {
    
    private func addViews () {
        self.addSubview(bannerImgView)
        self.addSubview(overlayView)
        self.addSubview(titleLbl)
        self.addSubview(hintLbl)
        self.addConstraints()
        self.setGradientBackground()
    }
    
    private func addConstraints () {
        bannerImgView.snp.makeConstraints { (make) in
            make.width.height.top.leading.equalToSuperview()
        }
        
        overlayView.snp.makeConstraints { (make) in
            make.width.height.top.leading.equalToSuperview()
        }
        
        hintLbl.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.height.equalTo(16)
            make.bottom.equalToSuperview().inset(18)
        }
        
        titleLbl.snp.makeConstraints { (make) in
            make.bottom.equalTo(hintLbl.snp.top).offset(-4)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        
    }
    
    private func setGradientBackground () {
        let colorTop = UIColor.red.cgColor
        let colorBottom = UIColor.blue.cgColor
        let gradientLayer = CAGradientLayer()
        
        gradientLayer.colors = [colorTop, colorBottom]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.frame = self.overlayView.bounds
        self.overlayView.layer.insertSublayer(gradientLayer, at: 0)
    }
}
